package com.dou.sample.baserecycleradapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by Dou on 2018/1/10.
 */

public class ViewHolder extends RecyclerView.ViewHolder {

    View mConvertView;
    Context mContext;

    SparseArray<View> mViews;

    public ViewHolder(Context context, View itemView) {
        super(itemView);
        mContext = context;
        mConvertView = itemView;
        mViews = new SparseArray<>();
    }

    public static ViewHolder get(Context context, int layoutID, ViewGroup parent){
        View view = LayoutInflater.from(context).inflate(layoutID, parent, false);
        return new ViewHolder(context, view);
    }

    public <T extends View> T findView(int resID){
        View view = mViews.get(resID);

        if (view == null) {
            view = mConvertView.findViewById(resID);
            mViews.put(resID, view);
        }

        return (T)view;
    }

    public void setText(int resID, String text){
        TextView textView = findView(resID);
        textView.setText(text);
    }

    public void setImageResource(int resID, int imageResID){
        ImageView imageView = findView(resID);
        imageView.setImageResource(imageResID);
    }

    public void setOnClickListener(int resID, View.OnClickListener listener){
        View view = findView(resID);
        view.setOnClickListener(listener);
    }
}
